<template>
    <div>
        <!--查询-->
        <el-form :inline="true" :model="form" class="demo-form-inline" size="mini">
            <el-form-item label="姓名">
                <el-input v-model="form.userName" placeholder="输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="form.state" placeholder="请选择" >
                    <el-option label="全部" value=""></el-option>
                    <el-option label="可用" value="0"></el-option>
                    <el-option label="禁用" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="findList">查询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="danger" @click="addInstructorAction">添加</el-button>
            </el-form-item>
        </el-form>

        <!--列表-->
        <el-table :data="paramData" stripe highlight-current-row v-loading="listLoading" style="width: 100%;">
            <el-table-column prop="name" label="姓名" align="center"></el-table-column>
            <el-table-column prop="mobile" label="手机号码" align="center"></el-table-column>
            <el-table-column prop="areas" label="所属区域"  :formatter="formatAreas" align="center"></el-table-column>
            <el-table-column prop="state" label="状态" :formatter="formatState" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button size="small" @click="dialogForm(scope.row)">修改</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-pagination
                    background
                    layout="prev, pager, next" :page-size="pageSize"
                    :total="total"
                    style="float:right;"@current-change="changePage"
                    :current-page.sync="currentPage">
            </el-pagination>
        </el-col>

        <el-dialog :title="title" :visible.sync="dialogFormVisible" :before-close="handleClose">
            <el-form :model="dialogFormData" :rules="rules" ref="dialogFormData">
                <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
                    <el-input v-model="dialogFormData.name"  auto-complete="off" placeholder="输入姓名"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" :label-width="formLabelWidth" prop="mobile">
                    <el-input v-model="dialogFormData.mobile" auto-complete="off" placeholder="输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="所属区域" :label-width="formLabelWidth">
                    <el-checkbox-group v-model="dialogFormData.areasParams" @change="changeAreas">
                        <el-checkbox v-for="areaAll in areasList" :label="areaAll.id" :key="areaAll.id">
                            {{areaAll.title}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item  label="状态" :label-width="formLabelWidth">
                    <el-radio v-model="dialogFormData.state" :label="0">可用</el-radio>
                    <el-radio v-model="dialogFormData.state" :label="1">禁用</el-radio>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dissmiss">取 消</el-button>
                <el-button type="primary" @click="comfortUpdate">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>
<script>
    import util from '../../common/js/util'
    import * as api from '../../api/enjoylove_api';

    export default {
        data() {
            var validateMobile = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('手机号不能为空'));
                } else {
                    if (this.dialogFormData.mobile !== '' ) {
                        if(!(/^1(3|4|5|7|8)\d{9}$/.test(this.dialogFormData.mobile))){
                            callback(new Error('手机号格式有误'));
                        }
                    }
                    callback();
                }
            };

            return {
                paramData:[],//数据源
                areasList:[],//区域数据
                title:'',
                listLoading:false,
                total:0,
                currentPage :1,
                pageSize :10,
                //添加修改框
                dialogFormVisible: false,
                //获取列表
                form: {
                    userName: '',
                    state:''
                },
                //添加/更新
                dialogFormData:{
                    id:'',
                    name:'',
                    mobile:'',
                    state:'',
                    areasParams:[]
                },
                formLabelWidth: '120px',
                radio:'1',
                checked :false,
                rules: {
                    name: [{required: true, message: '姓名不能为空', trigger: 'blur'}],
                    mobile: [{required: true,validator: validateMobile, trigger: 'blur'}],
                }
            }

        },
        methods:{
            //获取列表数据
              getData (){
                  this.listLoading = true;
                  /**********数据初始化****/
                  this.dialogFormData.name = '';
                  this.dialogFormData.mobile = '';
                  this.dialogFormData.state=0;
                  this.dialogFormData.areasParams=[];
                  this.dialogFormData.id='';
                  /********************/
                  let  params={
                      page:this.currentPage,
                      name:this.form.userName,
                      state:this.form.state,
                  }
                  api.getInstructorList(params).then((res) => {
                      this.listLoading = false;//停止加载
                      var _resData  =JSON.parse(res.data) ;
                      if(!_resData.status){
                          if(_resData.success){
                              //成功
                              this.paramData = _resData.data.instructorPage.content;
                              this.total = _resData.data.instructorPage.totalElements;
                          }else {
                              this.$message.error(_resData.message);
                          }
                      }else{
                          if(_resData.status == 401){
                              this.$router.push('/login');
                          }
                      }


                  });
             },
            formatAreas(row){
                  if(row.areas.length>0){
                      var areaS = ''
                      for(let index in row.areas){
                          areaS+=row.areas[index].title+'  '
                      }
                      return  areaS ;
                  }else {
                      return '--'
                  }
            },
            formatState(row){
                return row.state==1? '禁用':"可用"
            },
            //选择页码
            changePage(val){
                this.currentPage = val;
                this.getData();
            },
            //查询按钮
            findList(){
                this.currentPage =1;
                this.getData();
            },
            //修改按钮
            dialogForm(row){
                this.title = '编辑辅导',
                this.dialogFormVisible = true;
                this.dialogFormData.name = row.name;
                this.dialogFormData.mobile = row.mobile;
                if(row.state==''){
                    row.state = 0;
                }
                this.dialogFormData.state = row.state;
                for (var index in row.areas){
                    this.dialogFormData.areasParams.push(row.areas[index].id);
                }
                this.dialogFormData.id = row.id;
            },
            //多选框选择区域
            changeAreas(value){
                this.dialogFormData.areasParams = value;
            },
            //取消按钮
            dissmiss(){
                this.$refs['dialogFormData'].resetFields();
                this.dialogFormVisible = false;
                this.dialogFormData.name = '';
                this.dialogFormData.mobile = '';
                this.dialogFormData.state=0;
                this.dialogFormData.areasParams=[];
                this.dialogFormData.id='';

            },
            //确定修改
            comfortUpdate(){

                //验证参数
                this.$refs['dialogFormData'].validate((valid) => {
                    if (valid) {
                        if( this.title=='编辑辅导'){
                            this.updateData();
                        }else {
                            this.addInstructor();
                        }
                        this.dialogFormVisible = false;
                    }
                });
            },
            // 修改数据
            updateData (){
                let  params={
                    name:this.dialogFormData.name,
                    mobile:this.dialogFormData.mobile,
                    state:this.dialogFormData.state,
                    areas:this.dialogFormData.areasParams,
                    id:this.dialogFormData.id,
            }
                api.updateInstructor(params).then((res) => {
                    this.getData();
                    var _resData  =JSON.parse(res.data) ;
                    this.$refs['dialogFormData'].resetFields();
                    if(!_resData.status){
                        if(_resData.success){
                            this.dialogFormData.name = '';
                            this.dialogFormData.mobile = '';
                            this.dialogFormData.state=0;
                            this.dialogFormData.areasParams=[];
                            this.dialogFormData.id='';

                            //成功
                            this.$message({
                                message: '保存成功!',
                                type: 'success'
                            });
                        }else {
                            this.$message.error(_resData.message);
                        }

                    }else {
                        if (_resData.status == 401) {
                            this.$router.push('/login');
                        }else {
                            this.$message.error('保存失败!');
                        }
                    }
                });
            },
            //获取区域列表
            getAreasList(){
                let params ={};
               api.getInstructorAreas(params).then((res)=>{
                   var _resData  =JSON.parse(res.data) ;
                   if(!_resData.status){
                       if(_resData.success){
                           this.areasList = _resData.data.areas;
                       }else {
                           this.$message.error(_resData.message);
                       }
                   }else {
                       if (_resData.status == 401) {
                           this.$router.push('/login');
                       }
                   }
               });
            },
            addInstructorAction(){
                this.title = '添加辅导';
                this.dialogFormVisible = true;
            },
            addInstructor(){
                let  params={
                    name:this.dialogFormData.name,
                    mobile:this.dialogFormData.mobile,
                    state:this.dialogFormData.state,
                    areas:this.dialogFormData.areasParams,
                }
                api.addInstructor(params).then((res) => {
                    this.getData();
                    this.$refs['dialogFormData'].resetFields();
                    var _resData  =JSON.parse(res.data) ;
                    if(!_resData.status){
                        if(_resData.success){
                            this.dialogFormData.name = '';
                            this.dialogFormData.mobile = '';
                            this.dialogFormData.state=0;
                            this.dialogFormData.areasParams=[];
                            this.dialogFormData.id='';

                            //成功
                            this.$message({
                                message: '保存成功!',
                                type: 'success'
                            });
                        }else {
                            this.$message.error(_resData.message);
                        }

                    }else {
                        if (_resData.status == 401) {
                            this.$router.push('/login');
                        }else {
                            this.$message.error('保存失败!');
                        }
                    }
                });
            },
            cheackForm(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        return true;
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            //关闭 dialog 按钮
            handleClose(done){
                this.dialogFormData.name = '';
                this.dialogFormData.mobile = '';
                this.dialogFormData.state=0;
                this.dialogFormData.areasParams=[];
                this.dialogFormData.id='';
                done();
            }

        },
        mounted() {
            this.$nextTick(function () {
                this.getData();
                this.getAreasList();
            })

        }
    }
</script>